package com.infoland.afanmall.model.shopCart.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.daimajia.swipe.util.Attributes;
import com.infoland.afanmall.R;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.DecimalKit;
import com.infoland.afanmall.base.util.Keyboard;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.UserKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.order.activity.OrderDownActivity;
import com.infoland.afanmall.model.shopCart.adapter.CartAdapter;
import com.infoland.afanmall.model.shopCart.entity.CartGoodEntity;
import com.infoland.afanmall.model.shopCart.entity.ShopCartEntity;
import com.jaeger.library.StatusBarUtil;
import com.vondear.rxtools.RxTool;
import com.wang.avi.AVLoadingIndicatorView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ShopCartActivity extends AppCompatActivity {
    @BindView(R.id.net_scro)
    NestedScrollView net_scro;
    @BindView(R.id.cart_list)
    RecyclerView cartList;
    @BindView(R.id.cart_back)
    LinearLayout cartBack;
    @BindView(R.id.cart_edit)
    TextView cartEdit;
    @BindView(R.id.cart_ll1)
    LinearLayout cartLl1;
    @BindView(R.id.cart_goods_total)
    TextView cartGoodsTotal;
    @BindView(R.id.cart_settlement)
    TextView cartSettlement;
    @BindView(R.id.cart_foot)
    LinearLayoutCompat cartFoot;
    @BindView(R.id.delete_btn_2)
    TextView deleteBtn2;
    @BindView(R.id.cart_edit_foot)
    LinearLayoutCompat cartEditFoot;
    @BindView(R.id.cart_null)
    LinearLayoutCompat cartNull;
    @BindView(R.id.cart_content)
    LinearLayout cartContent;
    Keyboard keyboardLinster;
    List<ShopCartEntity> shopCartEntities;
    @BindView(R.id.cart_checkbox_all_1)
    CheckBox cartCheckboxAll1;
    @BindView(R.id.cart_check_all_2)
    CheckBox cartCheckAll2;
    public static List<TextView> textViewList1;
    public static List<TextView> textViewList2;
    public static List<CheckBox> checkBoxList;
    public static List<ShopCartEntity.CartListBean> cartListBeans;
    CartAdapter cartAdapter;
    ArrayList<Integer> ids;

    //    /***一堆点击事件**/
    @OnClick({R.id.cart_list, R.id.cart_back, R.id.cart_edit, R.id.cart_ll1, R.id.cart_checkbox_all_1, R.id.cart_goods_total, R.id.cart_settlement, R.id.cart_foot, R.id.cart_check_all_2, R.id.delete_btn_2, R.id.cart_edit_foot})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            /***点击编辑--事件*/
            case R.id.cart_edit:
                startLoading();
                for (CheckBox c : checkBoxList) {
                    c.setChecked(false);
                }
                cartCheckboxAll1.setChecked(false);
                cartCheckAll2.setChecked(false);
                updCheckPrice();
                String s = cartEdit.getText().toString();
                stopLoading();
                if ("编辑".equals(s)) {
                    cartEdit.setText("完成");
                    cartFoot.setVisibility(View.GONE);
                    cartEditFoot.setVisibility(View.VISIBLE);
                    for (int i = 0; i < textViewList1.size(); i++) {
                        textViewList1.get(i).setVisibility(View.GONE);
                        textViewList2.get(i).setVisibility(View.VISIBLE);
                    }
                } else {
                    cartEdit.setText("编辑");
                    cartEditFoot.setVisibility(View.GONE);
                    cartFoot.setVisibility(View.VISIBLE);
                    for (int i = 0; i < textViewList1.size(); i++) {
                        textViewList2.get(i).setVisibility(View.GONE);
                        textViewList1.get(i).setVisibility(View.VISIBLE);
                    }
                }

                break;

            case R.id.cart_list:
                break;

            case R.id.cart_ll1:
                break;
            case R.id.cart_checkbox_all_1:
                break;
            case R.id.cart_goods_total:
                break;

            case R.id.cart_foot:
                break;
            case R.id.cart_check_all_2:
                break;
            /***退出*/
            case R.id.cart_back:
                finish();
                ToolsKit.goCloseDh(this);
                break;
            /****点击结算*/
            case R.id.cart_settlement:
                getIds();
                int size = ids.size();
                if (size < 1) {
                    ToastUtils.showShort("请先勾选商品");
                } else {
                    boolean fastClick = RxTool.isFastClick(2000);
                    if (!fastClick) {
                        Bundle bundle = new Bundle();
                        bundle.putIntegerArrayList("ids", ids);
                        bundle.putString("now_type", CONST.ORDER_TYPE_CART);
                        LogKit.E("size  ", "  " + size);
                        ToolsKit.goDh(this, OrderDownActivity.class, bundle);
                        finish();
                        ToolsKit.goCloseDh(this);
                    } else {
                        LogKit.E(" 快速点击  ", " 快速点击 了 ");
                    }
                }
                break;
            /***点击删除时操作**/
            case R.id.delete_btn_2:
                getIds();
                if (ids.size() > 0) {
                    deleteByIds(ids);
                } else {
                    ToastUtils.showShort("请先勾选商品");
                }
                break;

        }
    }


    //    List<>
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cart_activity);
        ButterKnife.bind(this);
        initData();
        addKeyBodLinster();
        StatusBarUtil.setColor(this, ToolsKit.getColor(R.color.white));
//        StatusBarKit.immersive(this); //设置当前activity为沉浸
//        StatusBarKit.immersive();
//        StatusBarKit.setPaddingSmart(this, cartLl1);//只能添加padding
//        cartLl1.setBackgroundColor(R.color.white);
    }

    protected void initData() {
        checkBoxList = new ArrayList<>();
        textViewList1 = new ArrayList<>();
        textViewList2 = new ArrayList<>();
        startLoading();
        if (UserKit.isLogin()) {
            new OkHttpKit().send(
                    response200 -> {
                        stopLoading();
                        shopCartEntities = JSONArray.parseArray(response200, ShopCartEntity.class);
                        if (shopCartEntities.size() > 0) {
                            shouHaveGood();
                            cartListBeans = shopCartEntities.get(0).getCartList();
                            LogKit.E("cartListSize---> ", "  " + cartListBeans.size());
                            setAdapter();
                        } else {
                            shouNoGood();
                        }
                    },
                    success401 -> {
                        stopLoading();
                        shouNoGood();
                    },
                    error -> {
                        stopLoading();
                        shouNoGood();
                    }
            ).post(CONST.GET_USER_CART + UserKit.getAccessToken(), new JSONObject(), this);

        } else {
            stopLoading();
            shouNoGood();
        }
    }


    //    /****设置适配器*/
    private void setAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        cartList.setLayoutManager(linearLayoutManager);
        cartAdapter = new CartAdapter(cartCheckboxAll1, cartCheckAll2, this);
        cartAdapter.setMode(Attributes.Mode.Single);
        cartList.setAdapter(cartAdapter);

        /***点击ItemCheck事件回调*/
        cartAdapter.setCartCheckLinster(() -> {
            LogKit.E("  setCartCheckLinster ", " setCartCheckLinster ");
            String s = cartEdit.getText().toString();
            if ("编辑".equals(s)) {
                LogKit.E("   编辑", "  编辑");
                updCheckPrice();
            } else {

            }
        });

        /***更改数量回调*/
        cartAdapter.setCartCountLinster((int i, int position, EditText cartSubtraction, TextView goodsPrice, TextView cartGoodsPrice) -> {
            if (i == 1) {
                sub(position, cartSubtraction, goodsPrice, cartGoodsPrice);
            } else {
                add(position, cartSubtraction, goodsPrice, cartGoodsPrice);
            }
        });

        /***删除Item事件回调*/
        cartAdapter.setCartDeleteLinster((int id) -> {
            ids = new ArrayList<>();
            ids.add(id);
            deleteByIds(ids);
        });
    }

    //    /***添加商品数量*/
    private void add(int position, EditText cartGoodsCount, TextView cartGoodsPrice, TextView cartGoodsPrice2) {
        String s = cartGoodsCount.getText().toString();
        int count = Integer.valueOf(s);
        int i = count + 1;
        updThisPrice(i, position, cartGoodsCount, cartGoodsPrice, cartGoodsPrice2);
    }

    //    /***减少商品数量*/
    private void sub(int position, EditText cartGoodsCount, TextView cartGoodsPrice, TextView cartGoodsPrice2) {
        String s = cartGoodsCount.getText().toString();
        int count = Integer.valueOf(s);
        if (count <= 1) {
            ToastUtils.showShort("最小购买数量为 1");
        } else {
            int i = count - 1;
            updThisPrice(i, position, cartGoodsCount, cartGoodsPrice, cartGoodsPrice2);
        }
    }

    //    /***更新自己的价格*/
    private void updThisPrice(int count, int position, EditText cartGoodsCount, TextView goodsPrice, TextView cartGoodsPrice) {
        startLoading();
        /***查询库存**/
        int goods_id = cartListBeans.get(position).getGoods_id();
        /****根据商品id查询商品信息*/
        JSONObject para = new JSONObject();
        para.put("id", goods_id);
        new OkHttpKit().send(
                response200 -> {
                    stopLoading();
                    CartGoodEntity cartGoodEntity = JSONObject.parseObject(response200, CartGoodEntity.class);
                    int kucun = cartGoodEntity.getG_stock();
                    double goods_price = cartGoodEntity.getGoodsPrice().getGoods_price();
                    if (kucun >= count && kucun > 0) {
//                    RxTool.setEdDecimal();
                        BigDecimal mul = DecimalKit.mul(goods_price, count);
                        cartGoodsCount.setText(count + "");
                        cartListBeans.get(position).setGoods_count(count);
                        cartGoodsPrice.setText("￥" + mul + "");
                        goodsPrice.setText("￥" + mul + "");
                        updCheckPrice();
                    } else {
                        ToastUtils.showShort("库存不足");
                    }
                },
                success401 -> {
                    LogKit.E("success401 ---->   ", "  " + success401);
                },
                error -> {
                    LogKit.E("error ---->   ", "  " + error);
                }
        ).post(CONST.GOOD_INFO + UserKit.getAccessToken(), para, this);
    }

    //    /***更新选中之后的价格*/
    private void updCheckPrice() {
        BigDecimal price = new BigDecimal(0.00);
        for (int i = 0; i < checkBoxList.size(); i++) {
            if (checkBoxList.get(i).isChecked()) {
                ShopCartEntity.CartListBean cartListBean = cartListBeans.get(i);
                BigDecimal mul = DecimalKit.mul(cartListBean.getGoods_count(), cartListBean.getGoods_price());
                price = DecimalKit.add(mul, price);
            }
        }
        cartGoodsTotal.setText("￥" + price);
    }


    //    /***删除商品**/
    private void deleteByIds(ArrayList<Integer> ids) {
        JSONObject para = new JSONObject();
        para.put("ids", ids);

        new OkHttpKit().send(
                response200 -> {
                    JSONObject jsonObject = JSONObject.parseObject(response200);
                    if (jsonObject.getBoolean("success")) {
                        initData();
                    } else {
                        ToastUtils.showShort(jsonObject.getString("message"));
                    }
                },
                success401 -> {
                    LogKit.E("success401 ---->   ", "  " + success401);
                },
                error -> {
                    LogKit.E("error ---->   ", "  " + error);
                }
        ).post(CONST.DELETE_USER_CARTS + UserKit.getAccessToken(), para, this);
    }

    @Override
    protected void onDestroy() {
        ToolsKit.deleteOKHttp(this);
        keyboardLinster = null;
        super.onDestroy();
    }

    //    /****添加键盘监听*/
    private void addKeyBodLinster() {
        keyboardLinster = new Keyboard().registerActivity(this).setmKeyBodListener(keyboardVisible -> {
            if (keyboardVisible) {
                cartEditFoot.setVisibility(View.GONE);
                cartFoot.setVisibility(View.GONE);
            } else {
                String s = cartEdit.getText().toString();
                if ("完成".equals(s)) {

                    cartCheckAll2.setGravity(Gravity.CENTER);
                    cartEditFoot.setVisibility(View.VISIBLE);
                } else {
                    cartCheckboxAll1.setGravity(Gravity.CENTER);
                    cartFoot.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //    /***没有商品时展示界面*/
    private void shouNoGood() {
        cartContent.setVisibility(View.GONE);
        cartNull.setVisibility(View.VISIBLE);
        cartCheckboxAll1.setChecked(false);
        cartCheckAll2.setChecked(false);
    }

    //    /***购物车中有商品是展示界面*/
    private void shouHaveGood() {
        cartNull.setVisibility(View.GONE);
        cartContent.setVisibility(View.VISIBLE);
    }

    //    /***获取选中的购物车ID*/
    private void getIds() {
        ids = new ArrayList<>();
        for (int i = 0; i < checkBoxList.size(); i++) {
            if (checkBoxList.get(i).isChecked()) {
                ids.add(cartListBeans.get(i).getId());
            }
        }
    }

    @BindView(R.id.avi_pt)
    AVLoadingIndicatorView avi_pt;

    private void startLoading() {
        avi_pt.setVisibility(View.VISIBLE);
    }

    private void stopLoading() {
        new Handler().postDelayed(() -> {
            avi_pt.setVisibility(View.GONE);
        }, 200);
    }


    @Override
    public void onBackPressed() {
        finish();
        ToolsKit.goCloseDh(this);
    }

}
